﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace GlucometerPrototype
{
    class AeroGlassHelper
    {
        [DllImport("DwmApi.dll")]
        private static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins pMarInset);

        [StructLayout(LayoutKind.Sequential)]
        private struct Margins
        {
            public int cxLeftWidth;
            public int cxRightWidth;
            public int cyTopHeight;
            public int cyBottomHeight;
        }

        private static Margins GetDpiAdjustedMargins(IntPtr windowHandle, int left, int right, int top, int bottom)
        {
            //Get the system DPI
            System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(windowHandle);
            float desktopDpiX = g.DpiX;
            float desktopDpiY = g.DpiY;

            //Set the margins
            AeroGlassHelper.Margins margin = new AeroGlassHelper.Margins();
            margin.cxLeftWidth = Convert.ToInt32(left * (desktopDpiX / 96));
            margin.cxRightWidth = Convert.ToInt32(right * (desktopDpiX / 96));
            margin.cyTopHeight = Convert.ToInt32(top * (desktopDpiY / 96));
            margin.cyBottomHeight = Convert.ToInt32(bottom * (desktopDpiY / 96));

            return margin;
        }

        public static void ExtendGlass(Window win, int left, int right, int top, int bottom)
        {
            //Obtain the Win32 window handle for the WPF window
            WindowInteropHelper windowInterop = new WindowInteropHelper(win);
            IntPtr windowHandle = windowInterop.Handle;

            //Adjust the margins to take the system DPI into account
            Margins margins = GetDpiAdjustedMargins(windowHandle, left, right, top, bottom);

            //Extend the glass frame
            int returnVal = DwmExtendFrameIntoClientArea(windowHandle, ref margins);
            if (returnVal < 0)
            {
                throw new NotSupportedException("Operation failed.");
            }
        }
    }
}
